<template>
  <div class="app-container">
    <div class="module-title">
      <svg-icon icon-class="build" style="font-size:28px;margin-right:8px;"/>
      <span>工单管理</span>
      <span class="module-desc">管理生产工单与进度</span>
    </div>
    <div class="module-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable
            prefix-icon="el-icon-search"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="上传状态" prop="uploadStatus">
          <el-select v-model="queryParams.uploadStatus" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="已上传" value="已上传" />
            <el-option label="未上传" value="未上传" />
            <el-option label="上传失败" value="上传失败" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="goAddPage"
            v-hasPermi="['production:production:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
            v-hasPermi="['production:production:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['production:production:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['production:production:export']">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-s-order" size="mini" @click="handleImportFromBom"
            v-hasPermi="['production:production:import']">从BOM导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-shopping" size="mini" :disabled="single" @click="handlePickingFromSelection"
            v-hasPermi="['production:production:picking']">领料</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-refresh-left" size="mini" :disabled="single" @click="handleGenerateReturnMaterials"
            v-hasPermi="['production:production:return']">生成退料单</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="productionList" @selection-change="handleSelectionChange" 
        stripe border size="small" :default-sort="{prop: 'lastModifyTime', order: 'descending'}">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="工单ID" align="center" prop="orderId" />
        <el-table-column label="产品编号" align="center" prop="productId" />
        <el-table-column label="销售订单号" align="center" prop="salesOrder" />
        <el-table-column label="上传状态" align="center" prop="uploadStatus" width="100">
          <template slot-scope="scope">
            <el-tag :type="getUploadStatusType(scope.row.uploadStatus)" size="mini">
              <i :class="getUploadStatusIcon(scope.row.uploadStatus)" style="margin-right: 4px;"></i>
              {{ scope.row.uploadStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="物料编码" align="center" prop="materialId" />
        <el-table-column label="工单数量" align="center" prop="orderQuantity" />
        <el-table-column label="已完成数量" align="center" prop="completedQuantity" />
        <el-table-column label="进度" align="center" width="120">
          <template slot-scope="scope">
            <el-progress 
              :percentage="getProgressPercentage(scope.row)" 
              :color="getProgressColor(scope.row)"
              :stroke-width="8"
              :show-text="false">
            </el-progress>
            <div class="progress-text">{{ getProgressPercentage(scope.row) }}%</div>
          </template>
        </el-table-column>
        <el-table-column label="计划开始时间" align="center" prop="plannedStartDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.plannedStartDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划完成日期" align="center" prop="plannedFinishDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.plannedFinishDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注信息" align="center" prop="remarks" />
        <el-table-column label="物料名称" align="center" prop="materialName" />
        <el-table-column label="可用库存" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ availableByMaterialId[scope.row.materialId] !== undefined ? availableByMaterialId[scope.row.materialId] : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入库数量" align="center" prop="inboundQuantity" />
        <el-table-column label="未入库数量" align="center" prop="remainingQuantity" />
        <el-table-column label="创建人" align="center" prop="creator" />
        <el-table-column label="最后修改人" align="center" prop="lastModifier" />
        <el-table-column label="修改时间" align="center" prop="lastModifyTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.lastModifyTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-shopping" @click="handlePicking(scope.row)" 
              :disabled="!isRowSelected(scope.row)">领料</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['production:production:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['production:production:remove']">删除</el-button>

            <el-button size="mini" type="text" icon="el-icon-refresh-left" @click="handleGenerateReturnMaterialsFromRow(scope.row)"
              v-hasPermi="['production:production:return']" v-if="scope.row.completedQuantity > 0">生成退料单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改工单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productId">
              <el-input v-model="form.productId" placeholder="请输入产品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售订单号" prop="salesOrder">
              <el-input v-model="form.salesOrder" placeholder="请输入销售订单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上传状态" prop="uploadStatus">
              <el-select v-model="form.uploadStatus" placeholder="请选择上传状态">
                <el-option label="未上传" value="未上传" />
                <el-option label="已上传" value="已上传" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialId">
              <el-input v-model="form.materialId" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单数量" prop="orderQuantity">
              <el-input v-model.number="form.orderQuantity" type="number" min="0" placeholder="请输入工单数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="已完成数量" prop="completedQuantity">
              <el-input v-model.number="form.completedQuantity" type="number" min="0" placeholder="请输入已完成数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库数量" prop="inboundQuantity">
              <el-input v-model.number="form.inboundQuantity" type="number" min="0" placeholder="请输入入库数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="未入库数量" prop="remainingQuantity">
              <el-input v-model.number="form.remainingQuantity" type="number" min="0" placeholder="请输入未入库数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="plannedStartDate">
              <el-date-picker clearable v-model="form.plannedStartDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择计划开始时间" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划完成日期" prop="plannedFinishDate">
              <el-date-picker clearable v-model="form.plannedFinishDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择计划完成日期" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人" prop="creator">
              <el-input v-model="form.creator" placeholder="请输入创建人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最后修改人" prop="lastModifier">
              <el-input v-model="form.lastModifier" placeholder="请输入最后修改人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注信息" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注信息" />
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduction, getProduction, delProduction, addProduction, updateProduction } from "@/api/production/production"
import { listProduction_detail } from '@/api/production_detail/production_detail'

import { addReturnMaterials } from '@/api/returnMaterials/returnMaterials'
import ProductionDetailTable from '@/views/production_detail/production_detail/ProductionDetailTable.vue'
import { listInventory } from "@/api/storage/inventory"

export default {
  activated(){
      this.getList()
  },
  name: "Production",
  components: { ProductionDetailTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单管理表格数据
      productionList: [],
      // 物料ID -> 可用库存 映射（仅统计状态=正常，quantity - lockedQuantity）
      availableByMaterialId: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: null,
        uploadStatus: null,
        dateRange: []
      },
      // 表单参数
      form: {
        orderId: null,
        productId: null,
        salesOrder: null,
        uploadStatus: null,
        materialId: null,
        orderQuantity: null,
        completedQuantity: null,
        plannedStartDate: null,
        plannedFinishDate: null,
        remarks: null,
        materialName: null,
        inboundQuantity: null,
        remainingQuantity: null,
        plannedFinishTime: null,
        plannedStartTime: null,
        creator: null,
        lastModifier: null,
        lastModifyTime: null,
        details: [] // 子表数据
      },
      // 表单校验
      rules: {
        orderQuantity: [
          { required: true, message: '请输入工单数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '工单数量必须大于0', trigger: 'blur' }
        ],
        completedQuantity: [
          { type: 'number', min: 0, message: '已完成数量不能小于0', trigger: 'blur' },
          { validator: this.validateCompletedQuantity, trigger: 'blur' }
        ],
        inboundQuantity: [
          { type: 'number', min: 0, message: '入库数量不能小于0', trigger: 'blur' }
        ],
        materialName: [
          { required: true, message: '请输入物料名称', trigger: 'blur' }
        ],
        salesOrder: [
          { required: true, message: '请输入销售订单号', trigger: 'blur' }
        ]
      },
      // 日期选择器快捷选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    }
  },
  watch: {
    'form.orderQuantity': function(newVal) {
      // 当工单数量变化时，重新验证已完成数量
      if (this.form.completedQuantity && this.form.completedQuantity > newVal) {
        this.$nextTick(() => {
          this.$refs.form.validateField('completedQuantity');
        });
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询工单管理列表 */
    getList() {
      this.loading = true
      listProduction(this.queryParams).then(response => {
        this.productionList = response.rows
        this.total = response.total
        // 计算当前页每个物料的可用库存
        this.computeAvailableForPage()
        this.loading = false
      })
    },
    // 计算当前页物料的可用库存（按 materialId 聚合，状态=正常，扣减锁定量）
    computeAvailableForPage() {
      const uniqueMaterialIds = Array.from(new Set((this.productionList || []).map(row => row.materialId).filter(id => id !== null && id !== undefined && id !== '')))
      if (uniqueMaterialIds.length === 0) {
        this.availableByMaterialId = {}
        return
      }
      const requests = uniqueMaterialIds.map(materialId => {
        const params = {
          pageNum: 1,
          pageSize: 9999,
          materialId: materialId,
          status: 1
        }
        return listInventory(params).then(resp => {
          const rows = resp.rows || []
          const sum = rows.reduce((acc, item) => {
            const quantity = Number(item.quantity || 0)
            const locked = Number(item.lockedQuantity || 0)
            return acc + (quantity - locked)
          }, 0)
          return { materialId, sum }
        }).catch(() => ({ materialId, sum: 0 }))
      })
      Promise.all(requests).then(results => {
        const map = {}
        results.forEach(({ materialId, sum }) => { map[materialId] = sum })
        this.availableByMaterialId = map
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        productId: null,
        salesOrder: null,
        uploadStatus: null,
        materialId: null,
        orderQuantity: null,
        completedQuantity: null,
        plannedStartDate: null,
        plannedFinishDate: null,
        remarks: null,
        materialName: null,
        inboundQuantity: null,
        remainingQuantity: null,
        plannedFinishTime: null,
        plannedStartTime: null,
        creator: null,
        lastModifier: null,
        lastModifyTime: null,
        details: [] // 子表数据
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.uploadStatus = null
      this.queryParams.dateRange = []
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    goAddPage() {
      this.$router.push({ path: '/production/production/add' });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const orderId = row.orderId || this.ids
      getProduction(orderId).then(response => {
        this.form = response.data
        
        this.open = true
        this.title = "修改工单管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 额外验证：确保已完成数量不超过工单数量
          if (this.form.completedQuantity > this.form.orderQuantity) {
            this.$message.error('已完成数量不能超过工单数量');
            return;
          }
          
          // 额外验证：确保入库数量不超过工单数量
          if (this.form.inboundQuantity > this.form.orderQuantity) {
            this.$message.error('入库数量不能超过工单数量');
            return;
          }
          
          if (this.form.orderId != null) {
            updateProduction(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addProduction(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids
      this.$modal.confirm('是否确认删除工单管理编号为"' + orderIds + '"的数据项？').then(function () {
        return delProduction(orderIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('production/production/export', {
        ...this.queryParams
      }, `production_${new Date().getTime()}.xlsx`)
    },
    /** 获取上传状态标签类型 */
    getUploadStatusType(status) {
      switch(status) {
        case '已上传':
          return 'success'
        case '未上传':
          return 'warning'
        case '上传失败':
          return 'danger'
        default:
          return 'info'
      }
    },
    
    /** 获取上传状态图标 */
    getUploadStatusIcon(status) {
      switch(status) {
        case '已上传':
          return 'el-icon-circle-check'
        case '未上传':
          return 'el-icon-upload'
        case '上传失败':
          return 'el-icon-circle-close'
        default:
          return 'el-icon-question'
      }
    },
    
    /** 获取进度百分比 */
    getProgressPercentage(row) {
      if (!row.orderQuantity || row.orderQuantity === 0) return 0;
      
      // 计算进度百分比
      let percentage = Math.round((row.completedQuantity / row.orderQuantity) * 100);
      
      // 限制进度最大值为100%
      if (percentage > 100) {
        percentage = 100;
      }
      
      return percentage;
    },
    
    /** 获取进度条颜色 */
    getProgressColor(row) {
      const percentage = this.getProgressPercentage(row);
      if (percentage >= 80) return '#67C23A';
      if (percentage >= 50) return '#E6A23C';
      return '#F56C6C';
    },
    
    /** 领料功能 */
    handlePicking(row) {
      // 跳转到领料单新增页面并传递工单数据
      this.$router.push({
        path: '/picking/picking/add',
        query: { 
          orderId: row.orderId,
          materialId: row.materialId,
          materialCode: row.materialId, // 若后端以编码等同ID，仍一并传递
          materialName: row.materialName,
          orderQuantity: row.orderQuantity,
          completedQuantity: row.completedQuantity,
          plannedStartDate: row.plannedStartDate,
          plannedFinishDate: row.plannedFinishDate,
          remarks: row.remarks
        }
      });
    },
    
    /** 从BOM导入工单 */
    handleImportFromBom() {
      this.$router.push('/bom/bom');
    },
    
    /** 从选中行进行领料 */
    handlePickingFromSelection() {
      if (this.single) {
        this.$modal.msgError('请选择一个工单');
        return;
      }
      
      const selectedRow = this.productionList.find(item => item.orderId === this.ids[0]);
      if (!selectedRow) {
        this.$modal.msgError('未找到选中的工单');
        return;
      }
      
      // 调用原有的领料方法
      this.handlePicking(selectedRow);
    },
    
    /** 检查行是否被选中 */
    isRowSelected(row) {
      return this.ids.includes(row.orderId);
    },


    /** 验证已完成数量不能超过工单数量 */
    validateCompletedQuantity(rule, value, callback) {
      if (value > this.form.orderQuantity) {
        callback(new Error('已完成数量不能超过工单数量'));
      } else {
        callback();
      }
    },
    /** 生成退料单 */
    handleGenerateReturnMaterials() {
      if (this.single) {
        this.$modal.msgError('请选择一个工单');
        return;
      }
      
      const selectedRow = this.productionList.find(item => item.orderId === this.ids[0]);
      if (!selectedRow) {
        this.$modal.msgError('未找到选中的工单');
        return;
      }
      
      // 检查工单状态
      if (selectedRow.completedQuantity === 0) {
        this.$modal.msgError('工单尚未开始生产，无法生成退料单');
        return;
      }
      
      this.$modal.confirm(`是否确认生成工单编号为"${selectedRow.orderId}"的退料单？`).then(() => {
        // 构造退料单数据
        const returnData = {
          documentType: '生产退料',
          workOrderId: selectedRow.orderId,
          materialId: selectedRow.materialId,
          materialName: selectedRow.materialName,
          specification: selectedRow.materialSpecification || '',
          materialCode: selectedRow.materialId,
          returnCode: `RT-${Date.now()}`,
          actualReturnQty: 0, // 实际退料数量，需要用户输入
          writeOffQty: 0, // 核销数量
          returnDate: new Date().toISOString().split('T')[0],
          auditStatus: '待审核',
          returnBy: (this.$store.getters.name === 'admin' ? '系统管理员' : this.$store.getters.name) || '系统',
          createdBy: (this.$store.getters.name === 'admin' ? '系统管理员' : this.$store.getters.name) || '系统',
          sourceDocument: `工单${selectedRow.orderId}`,
          remarks: `从工单${selectedRow.orderId}自动生成，物料：${selectedRow.materialName}`
        };
        
        // 跳转到退料单页面并传递数据
        this.$router.push({
          path: '/returnMaterials/returnMaterials/add',
          query: { 
            workOrderId: selectedRow.orderId,
            materialId: selectedRow.materialId,
            materialName: selectedRow.materialName,
            returnData: JSON.stringify(returnData)
          }
        });
      }).catch(() => { });
    },
    /** 生成退料单 (从行数据触发) */
    handleGenerateReturnMaterialsFromRow(row) {
      if (row.completedQuantity === 0) {
        this.$modal.msgError('工单尚未开始生产，无法生成退料单');
        return;
      }

      this.$modal.confirm(`是否确认生成工单编号为"${row.orderId}"的退料单？`).then(() => {
        // 构造退料单数据
        const returnData = {
          documentType: '生产退料',
          workOrderId: row.orderId,
          materialId: row.materialId,
          materialName: row.materialName,
          specification: row.materialSpecification || '',
          materialCode: row.materialId,
          returnCode: `RT-${Date.now()}`,
          actualReturnQty: 0, // 实际退料数量，需要用户输入
          writeOffQty: 0, // 核销数量
          returnDate: new Date().toISOString().split('T')[0],
          auditStatus: '待审核',
          returnBy: (this.$store.getters.name === 'admin' ? '系统管理员' : this.$store.getters.name) || '系统',
          createdBy: (this.$store.getters.name === 'admin' ? '系统管理员' : this.$store.getters.name) || '系统',
          sourceDocument: `工单${row.orderId}`,
          remarks: `从工单${row.orderId}自动生成，物料：${row.materialName}`
        };
        
        // 跳转到退料单页面并传递数据
        this.$router.push({
          path: '/returnMaterials/returnMaterials/add',
          query: { 
            workOrderId: row.orderId,
            materialId: row.materialId,
            materialName: row.materialName,
            returnData: JSON.stringify(returnData)
          }
        });
      }).catch(() => { });
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/styles/module-card.scss";

.module-title {
  display: flex;
  align-items: center;
  font-size: 22px;
  font-weight: 700;
  color: #2980b9;
  margin-bottom: 18px;
  .module-desc {
    font-size: 14px;
    color: #888;
    font-weight: 400;
    margin-left: 18px;
  }
}

.el-table {
  .el-table__body tr:hover > td {
    background: #eaf6ff !important;
  }
  
  .progress-text {
    text-align: center;
    font-size: 12px;
    color: #666;
    margin-top: 4px;
  }
}

// 搜索表单优化
.el-form--inline .el-form-item {
  margin-bottom: 16px;
}

// 表格列宽度优化
.el-table .el-table__body-wrapper {
  overflow-x: auto;
}
</style>
